from django.shortcuts import render

# Create your views here.

from utils.common_response import APIResponse
from .serializers import LoginSerializer, SMSLoginSerializer, RegisterSerializer
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.decorators import action
from .models import *
from libs.tx_sms import get_code, send_sms as sms
from django.core.cache import cache  # django的缓存，放进去，后期可以取出来，可以设置过期时间，默认放在内存中
from threading import Thread
import time
from utils.common_logger import logger


class UserMobileView(ViewSet):
    @action(methods=['GET'], detail=False)
    def check_mobile(self, request, *args, **kwargs):
        try:
            mobile = request.query_params.get('mobile')
            User.objects.get(mobile=mobile)
            return APIResponse(msg='手机号存在')
        except Exception as e:
            raise Exception('手机号不存在')

        # 发送短信接口

    @action(methods=['GET'], detail=False)
    def send_sms(self, request, *args, **kwargs):
        # 后续要保证发送短信接口安全
        # 1 取出手机号
        mobile = request.query_params.get('mobile')
        # 2 生成验证码，保存到 缓存中--》后续要取出来校验
        code = get_code()
        key = f'cache_code_{mobile}'
        logger.info(code)
        create_time = time.time()
        if cache.get(key):
            sms_data = cache.get(key)
            rest_time = int(create_time - sms_data[1])
            if rest_time < 60:
                return APIResponse(msg=f'短信已发送,稍后再发,还需{60 - rest_time}s')
        cache.set(key, (code, create_time))
        t = Thread(target=sms, args=[mobile, code])
        t.start()
        return APIResponse(msg='短信已发送')


class LoginView(GenericViewSet):
    serializer_class = LoginSerializer
    authentication_classes = ()
    permission_classes = ()

    @action(methods=['POST'], detail=False)
    def mul_login(self, request, *args, **kwargs):
        return self._login(request, *args, **kwargs)

    @action(methods=['POST'], detail=False)
    def sms_login(self, request, *args, **kwargs):
        return self._login(request, *args, **kwargs)

    def _login(self, request, *args, **kwargs):
        host = request.headers.get('Host')
        serializer = self.get_serializer(data=request.data, context={'Host': host})
        serializer.is_valid(raise_exception=True)
        token = serializer.context.get('token')
        username = serializer.context.get('username')
        icon = serializer.context.get('icon')
        return APIResponse(token=token, username=username, icon=icon)

    def get_serializer_class(self):
        if self.action == 'sms_login':
            return SMSLoginSerializer
        else:
            return LoginSerializer


class UserRegisterView(GenericViewSet):
    serializer_class = RegisterSerializer

    def create(self, request, *args, **kwargs):
        # 逻辑写在序列化类中
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return APIResponse(msg='注册成功')
